<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row)">报警记录
          </el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="state.addModal ? 'listInfoBtn active' : 'listInfoBtn'" @click="addBtn('mul')">
          <svg-icon :class="state.addModal ? 'active' : ''" class-name="search-icon" icon-class="xinzeng" />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn('mul')">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
        <oneclickDelivery style="margin:0 0 0 12px;"></oneclickDelivery>
      </template>
      <template v-slot:selectNamelist>
        预报警列表
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto" v-model="state.addModal"
        resize :mask="true" showFooter>
        <template #title>
          <div class="w100 h100 fsc mask_title">{{state.modalTitle}}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="分站编号" prop="stationCode">
                    <el-select clearable filterable v-model="state.formData.stationCode" placeholder="请选择"
                      @change="stationModelChange">
                      <el-option v-for="item in state.stationmodelList" :key="item.value"
                        :label="item.value+'/'+item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="测点选择" prop="pointId">
                    <el-select clearable filterable v-model="state.formData.pointId" placeholder="请选择"
                      @change="pointModelChange">
                      <el-option v-for="item in state.stationInNumList" :key="item.pointId" :label="item.pointId+'-'+item.sensorName
" :value="item.pointId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="地点" prop="place">
                    <el-input disabled v-model="state.formData.place" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="预报类型" prop="forecastType">
                    <el-select :disabled="!state.formData.pointId" clearable filterable
                      v-model="state.formData.forecastType" placeholder="请选择" @change="changeType">
                      <el-option v-for="item in state.forecastTypeList" :key="item.value" :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="state.formData.forecastType == '上限报警值'
                 || state.formData.forecastType == '上下限报警值'">
                  <el-form-item label="上限报警值" prop="upPrealarmValue">
                    <el-input v-model="state.formData.upPrealarmValue" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="state.formData.forecastType == '下限报警值'  
                || state.formData.forecastType == '上下限报警值'">
                  <el-form-item label="下限报警值" prop="downPrealarmValue">
                    <el-input v-model="state.formData.downPrealarmValue" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="延迟时间" prop="prealarmTimeout">
                    <el-select clearable filterable v-model="state.formData.prealarmTimeout" placeholder="请选择">
                      <el-option v-for="item in state.timeOut" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="延迟时间单位" prop="prealarmTimeoutUnit">
                    <el-select clearable filterable v-model="state.formData.prealarmTimeoutUnit" placeholder="请选择"
                      @change="changeType">
                      <el-option v-for="item in state.stationOutNumList" :key="item.timeValue" :label="item.label"
                        :value="item.timeValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 报警记录 -->
    <el-drawer v-model="state.drawerShow" direction="rtl" size="40%" close-on-click-modal :modal="true">
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>报警记录信息</span>
        </h4>
      </template>
      <template #default>
        <recordInfo :recordInfoList="state.recordInfoList" @querybjjlClick="querybjjlClick" 
        :bjjlObj="state.bjjlObj"
          :bjjlThead="state.bjjlObj.bjjlThead" @getPointDatapagebjjl="getPointDatapagebjjl"
          @getPointDatabjjl="getPointDatabjjl"></recordInfo>
      </template>
      <!-- <template #footer>
          <p>
            <el-button type="info">取消</el-button>
            <el-button type="primary">确定</el-button>
          </p>
      </template> -->
    </el-drawer>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import oneclickDelivery from "@/components/commonCom/oneclickDelivery";
  import recordInfo from "./alarmInfo/recordInfo";
  import {
    computed,
    reactive
  } from "vue";
    import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    table_headers
  } from '@/components/commonCom/table_headers';
  import axios from "@/utils/request"
  import usePagesStore from '@/store/modules/pages'
  import {
    getlistSitesList
  } from '@/api/config'
  import dayjs from 'dayjs'
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore()
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP
  components: {
    list_controller
  }
  const upload = ref(null)
  let state = reactive({
    bjjlObj: {
      bjjlThead: [{
        field: 'prealarmStartTime',
        title: '报警时间'
      }, {
        field: 'prealarmValue',
        title: '报警值'
      }, {
        field: 'prealarmEndTime',
        title: '结束时间'
      }, {
        field: 'accumulationTime',
        title: '累计时长'
      }],
      listTable: [],
      total: 0,
      alarmCount: undefined,
      accumulationTime: undefined
    },
    recordInfoList: [{
        col: 12,
        type: 'input',
        label: '报警次数',
        field: 'alarmCount',
        binddata: undefined
      },
      {
        col: 12,
        type: 'input',
        label: '累计报警时间',
        field: 'accumulationTime',
        binddata: undefined
      }
    ],
    fileList: [],
    dialogVisiblepictureCardPreview: false,
    dialogImageUrl: '',
    options: {
      tableheads: computed(() => table_headers.constantBasic),
      queryList: {
        dropdownUrl: '',
        querys: [{
          field: 'condition',
          title: '搜索',
          type: 'input',
          binddata: '',
          tip: '请输入传感器名称或地点'
        }, {
          field: 'forecastType',
          title: '预报类型',
          type: 'select',
          binddata: '',
          options: [{
            label: '上限报警',
            value: '上限报警'
          }, {
            label: '下限报警',
            value: '下限报警'
          }, {
            label: '上下限报警',
            value: '上下限报警'
          }],
        }],
        queryMap: new Map([
          ['sensorTypeId', 'safety_pointType'],
          ['deviceTypeId', 'safety_deviceType'],
          ['alarmTypeId', 'alarmType']
        ])
      },
      dataUrl: '/prealarm/basic/preInfo',
      delUrl: '/prealarm/basic/del',
      addUrl: '/prealarm/basic/add',
      descUrl: '/prealarm/basic/getById'
    },
    // 表单
    addModal: false,
    modalTitle: '新增预报警',
    formRef: null,
    formData: {

    },
    rules: {
      stationCode: [{
        required: true,
        message: '请选择分站编号',
        trigger: 'change'
      }],
      pointId: [{
        required: true,
        message: '请选择测点选择',
        trigger: 'change'
      }],
      place: [{
        required: true,
        message: '请输入地点',
        trigger: 'blur'
      }],
      forecastType: [{
        required: true,
        message: '请选择预报类型',
        trigger: 'change'
      }],
      upPrealarmValue: [{
        required: true,
        message: '请输入上限报警值',
        trigger: 'blur'
      }],
      downPrealarmValue: [{
        required: true,
        message: '请输入下限报警值',
        trigger: 'blur'
      }],
      prealarmTimeoutUnit: [{
        required: true,
        message: '请选择延迟时间单位',
        trigger: 'change'
      }],
      prealarmTimeout: [{
        required: true,
        message: '请输入延迟时间',
        trigger: 'blur'
      }]
    },
    editId: undefined,
    stationmodelList: [],
    stationInNumList: [],
    forecastTypeList: [{
        label: '上限报警',
        value: '上限报警'
      },
      {
        label: '下限报警',
        value: '下限报警'
      },
      {
        label: '上下限报警',
        value: '上下限报警'
      }
    ],
    stationOutNumList: [],
    timeOut: [],
   

  })
  // 查看按钮
  function lookBtn(row) {
    state.bjjlObj.pointId = row.pointId
    state.drawerShow = true
  }

  function querybjjlClick(data) {
    let obj = {
      prealarmEndTime: dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss.000'),
      prealarmStartTime: dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss.000'),
      pointId: state.bjjlObj.pointId,
      condition: state.bjjlObj.pointId.includes('A') ? 'A' : state.bjjlObj.pointId.includes('D') ? 'D' : 'M',
      pageNum: 1,
      pageSize: 10
    }
    state.bjjlObj.obj = obj
    // 历史预报警列表
    axios.post("/hisPointPrealarm/listPointPrealarm", state.bjjlObj.obj).then(res => {
      if (res.data.list != null) {
        state.recordInfoList[0].binddata = res.data.list[0].alarmCount
        state.recordInfoList[1].binddata = res.data.list[0].accumulationPrealarmTime
      }
    })
    getlistPointDetailPrealarm()
  }

  function getlistPointDetailPrealarm(obj) {
    axios.post("/hisPointPrealarm/listPointDetailPrealarm", state.bjjlObj.obj).then(res => {
      if (res.data.list != null) {
        state.bjjlObj.listTable = res.data.list
        state.bjjlObj.total=res.data.total
      }else{
        state.bjjlObj.listTable=[]
      }
    })
  }

  function getPointDatapagebjjl(val) {
    state.bjjlObj.obj.pageNum = val
    getlistPointDetailPrealarm()
  }

  function getPointDatabjjl(val) {
    state.bjjlObj.obj.pageNum = 1
    state.bjjlObj.obj.pageSize = val
    getlistPointDetailPrealarm()
  }

  // 新增按钮
  function addBtn(row) {
    state.modalTitle = '新增预报警'
    state.addModal = true
    state.formData = {
      prealarmTimeoutUnit: 1
    }
    state.editId = undefined
    state.fileList = []
  }
  // 编辑按钮
  function editBtn(row) {
    state.modalTitle = '编辑预报警'
    state.addModal = true
    axios.post(state.options.descUrl, {
      id: row.id
    }).then(res => {
      if (res.code == 200) {
        if (res.data.stationCode != null) {
          if (res.data.stationCode.split('/')[0]) {
            axios.post('/prealarm/basic/listPoints', {
              stationCode: res.data.stationCode.split('/')[0],
              status: 'D'
            }).then(res => {
              state.stationInNumList = res.data
            })
          }
        }
        state.formData = res.data
        if (res.data.isSwitch) {
          state.formData.forecastType = res.data.prealarmType
          state.forecastTypeList = [{
            label: res.data.highShow + '报警',
            value: 1
          }, {
            label: res.data.lowShow + '报警',
            value: 2
          }]
        } else {
          state.formData.forecastType = res.data.forecastType
          state.forecastTypeList = [{
              label: '上限报警值',
              value: '上限报警值'
            },
            {
              label: '下限报警值',
              value: '下限报警值'
            },
            {
              label: '上下限报警值',
              value: '上下限报警值'
            }
          ]
        }
        state.editId = res.data.id
      }
    })
  }

  function deleteBtn(row) {
    let ids = []
    if (row != 'mul') {
      ids = [row.id]
    } else {
      if (store.records.length > 0) {
        ids = store.records.map(item => {
          return item.id
        })
      } else {
        proxy.$modal.msgSuccess('请先勾选所要删除数据!');
      }
    }
      if (ids.length > 0) {
      ElMessageBox.confirm(
          '确定要删除该数据吗?',
          '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        .then(() => {
          axios.post(state.options.delUrl, ids).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
          getsubstationmodelList()

              ElMessage({
                type: 'success',
                message: res.msg,
              })
              store.records = []
            }
          })

        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '删除取消',
          })
        })
    }

  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        state.formData.mark = true
        if (state.formData.isSwitch) {
          state.formData.prealarmType = state.formData.forecastType
          delete state.formData.forecastType
        } else {
          state.formData.forecastType = state.formData.forecastType
        }
        if (state.editId) {
          state.formData.id = state.editId
          axios.post(state.options.addUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              getsubstationmodelList()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        } else {
          axios.post(state.options.addUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              getsubstationmodelList()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        }
      }
    })
  }

  function cancel() {
    state.addModal = false
  }

  function getsubstationmodelList() {
    getlistSitesList().then(res => {
      state.stationmodelList = Object.keys(res.data).map(item => {
        return {
          label: res.data[item],
          value: item
        }
      })
    })
    axios.get('prealarm/basic/attainAllForecastTypes').then(res => {
      state.options.queryList.querys[1].options = res.data.map(item => {
        return {
          label: item,
          value: item
        }
      })
    })

  }

  function stationModelChange(val) {
    axios.post('/prealarm/basic/listPoints', {
      stationCode: val,
      status: 'D'
    }).then(res => {
      state.formData.pointId = undefined
      state.stationInNumList = res.data
    })
  }

  function pointModelChange(val) {
    if (val) {
      state.stationInNumList.forEach(item => {
        if (val == item.pointId) {
          state.formData.place = item.placeName
          state.formData.sensorName = item.name
          state.formData.isSwitch = item.isSwitch
          if (item.isSwitch) {
            state.forecastTypeList = [{
              label: item.highShow + '报警',
              value: 1
            }, {
              label: item.lowShow + '报警',
              value: 2
            }]
          } else {
            state.forecastTypeList = [{
                label: '上限报警值',
                value: '上限报警值'
              },
              {
                label: '下限报警值',
                value: '下限报警值'
              },
              {
                label: '上下限报警值',
                value: '上下限报警值'
              }
            ]
          }
        }
      })
    } else {
      state.formData.place = undefined
    }
  }
  getsubstationmodelList()

  // 选择预报类型
  const changeType = (val) => {
    if (val == '上限报警值') {
      state.formData.downPrealarmValue = null
    } else if (val == '下限报警值') {
      state.formData.upPrealarmValue = null
    }
  }
  // 获取延迟时间
  const getDelayTime = () => {
    axios.get('/prealarm/basic/getMinutes').then(res => {
      state.timeOut = res.data
    })
  }
  getDelayTime()
  // 获取延迟时间单位
  const getDelayTimeUnit = () => {
    axios.get('/prealarm/basic/getUnits').then(res => {
      state.stationOutNumList = res.data
    })
  }
  getDelayTimeUnit()
</script>
<style lang="scss" scoped>
  ::v-deep .el-drawer {
    .querycss {
      .fsc {
        &:nth-child(2) {
          display: none;
        }
      }
    }

    .table_box {
      .fsc {
        display: none;
      }
    }
  }
</style>